<template>
  <div class="simple-cart-container">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <h2>我的购物车</h2>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <div class="product-item" v-for="item in cartItems" :key="item.id">
        <div class="product-select">
          <a-checkbox v-model:checked="item.checked" @change="(e) => handleItemSelect(item.id, e.target.checked)"
            :disabled="!item.valid"></a-checkbox>
        </div>
        <div class="product-image">
          <img :src="item.image" alt="商品图片">
        </div>
        <div class="product-info">
          <div class="product-title">{{ item.title }}</div>
          <div class="product-spec">{{ item.spec }}</div>
          <div class="product-status" v-if="!item.valid">
            <a-tag color="red">失效</a-tag>
          </div>
          <div class="product-actions" v-else>
            <a href="javascript:;" @click="handleDelete(item.id)">
              <delete-outlined /> 删除
            </a>
          </div>
        </div>
        <div class="product-price">
          <div class="current-price">¥{{ item.price.toFixed(2) }}</div>
          <div class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice.toFixed(2) }}</div>
        </div>
        <div class="product-quantity">
          <a-input-number v-model:value="item.quantity" :min="1" :max="99" size="small" :disabled="!item.valid"
            @change="handleQuantityChange(item.id, item.quantity)" />
        </div>
        <div class="product-subtotal">
          <template v-if="item.valid">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </template>
          <template v-else>--</template>
        </div>
      </div>
    </div>

    <!-- 结算栏 -->
    <div class="cart-footer">
      <div class="footer-left">
        <a-checkbox v-model:checked="selectAll" @change="handleSelectAll">全选</a-checkbox>
        <a-button type="text" @click="handleClearInvalid">清除失效商品</a-button>
        <span class="total-count">共 {{ cartItems.length }} 件</span>
      </div>
      <div class="footer-right">
        <div class="total-info">
          <span class="total-text">已选 {{ selectedCount }} 件</span>
          <span class="total-price">
            合计: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </span>
          <span class="discount-text">优惠: ¥{{ discount.toFixed(2) }}</span>
        </div>
        <a-button type="primary" size="large" :disabled="selectedCount === 0" @click="handleCheckout">
          结算({{ selectedCount }})
        </a-button>
      </div>
    </div>
    <PayModal ref="paymentModal" :amount="totalPrice" @success="handlePaymentSuccess" @cancel="handlePaymentCancel" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import {
  HeartOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { getAllCar, updateCarById, clearCar } from '@/apis/user/car';
import PayModal from '@/components/payModal.vue';
import { addOrder } from '@/apis/user/order';


// 购物车数据
const cartItems = ref([]);

// 全选状态
const selectAll = ref(false);

// 计算属性
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.checked && item.valid).length;
});

const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.checked && item.valid)
    .reduce((sum, item) => sum + (item.price * item.quantity), 0);
});

const discount = computed(() => {
  return cartItems.value
    .filter(item => item.checked && item.valid && item.originalPrice)
    .reduce((sum, item) => sum + ((item.originalPrice - item.price) * item.quantity), 0);
});

// 方法
const handleSelectAll = (e) => {
  const checked = e.target.checked;
  cartItems.value.forEach(item => {
    if (item.valid) {
      item.checked = checked;
    }
  });
};

const handleItemSelect = (itemId, checked) => {
  const item = cartItems.value.find(i => i.id === itemId);
  if (item) {
    item.checked = checked;
    updateSelectAll();
  }
};

const updateSelectAll = () => {
  const validItems = cartItems.value.filter(item => item.valid);
  selectAll.value = validItems.length > 0 && validItems.every(item => item.checked);
};

const handleQuantityChange = (itemId, quantity) => {
  updateCarById(itemId, { num: quantity })
};


const handleDelete = (itemId) => {
  Modal.confirm({
    title: '删除',
    content: '你确定要删除吗？',
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      clearCar({
        car_id: [itemId]
      }).then(res => {
        if (res.code === 0) {
          cartItems.value = cartItems.value.filter(item => item.id !== itemId);
          message.success('删除成功');
          updateSelectAll();
        }
      })
    }
  });
};

const handleClearInvalid = () => {
  const data = cartItems.value.filter(item => !item.valid).map(item => item.id);
  if (!data.length) return;
  clearCar({
    car_id: data
  }).then(res => {
    if (res.code === 0) {
      cartItems.value = cartItems.value.filter(item => item.valid);
      message.success('已清除失效商品');
    }
  })
};

const paymentModal = ref(null);
const handleCheckout = () => {
  const selectedProducts = cartItems.value.filter(item => item.checked && item.valid);
  console.log('结算商品:', selectedProducts);
  message.success(`正在结算 ${selectedProducts.length} 件商品`);

  paymentModal.value.open();
  // 实际项目中跳转到结算页面
};

const handlePaymentSuccess = (result) => {
  // 处理支付成功逻辑
  const selectedProducts = cartItems.value.filter(item => item.checked && item.valid)
  const product = JSON.stringify(selectedProducts);
  const order_amount = result.amount;
  addOrder({
    product,
    order_amount,
    order_status: 2
  }).then(res => {
    if (res.code === 0) {
      handlePayAfter(selectedProducts.map(item=>item.id))
    }
  })
};

const handlePaymentCancel = (result) => {
  // 处理取消支付逻辑
  const selectedProducts = cartItems.value.filter(item => item.checked && item.valid)
  const product = JSON.stringify(selectedProducts);
  const order_amount = result.amount;
  addOrder({
    product,
    order_amount,
    order_status: 1
  }).then(res => {
    if(res.code=== 0){
      handlePayAfter(selectedProducts.map(item=>item.id))
    }
  })
};

function handlePayAfter(itemIds) {
  clearCar({
    car_id: itemIds
  }).then(res => {
    if (res.code === 0) {
      getAllMyCar();
    }
  })
}

function getAllMyCar() {
  getAllCar().then(res => {
    cartItems.value = res.data.list.map(item => {
      const findOne = cartItems.value.find(prod => prod.id === item.product_id);
      return {
        id: item.car_id,
        title: item.productInfo?.name || '失效商品',
        spec: item.productInfo?.desc,
        image: item.productInfo?.image,
        price: Number(item.productInfo?.current_price || item.productInfo?.price),
        originalPrice: Number(item.productInfo?.price),
        quantity: item.num,
        checked: findOne?.checked || false,
        valid: !!item.productInfo

      }
    })

  })
}
getAllMyCar();


// 初始化时更新全选状态
onMounted(() => {
  updateSelectAll();
});
</script>

<style scoped>
.simple-cart-container {
  position: relative;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cart-header h2 {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.cart-operations {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-list {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-select {
  width: 40px;
  text-align: center;
}

.product-image {
  width: 80px;
  height: 80px;
  margin: 0 10px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  min-width: 0;
  margin-right: 20px;
}

.product-title {
  font-size: 14px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.product-status {
  margin-top: 5px;
}

.product-actions {
  display: flex;
  gap: 15px;
  margin-top: 5px;
}

.product-actions a {
  font-size: 12px;
  color: #666;
}

.product-price {
  width: 120px;
  text-align: center;
}

.current-price {
  font-size: 16px;
  color: #ff0036;
  font-weight: bold;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.product-quantity {
  width: 120px;
  text-align: center;
}

.product-subtotal {
  width: 120px;
  text-align: right;
  font-size: 16px;
  color: #ff0036;
  font-weight: bold;
  padding-right: 10px;
}

.cart-footer {
  position: absolute;
  bottom: 0;
  left: 0px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-count {
  font-size: 14px;
  color: #666;
}

.footer-right {
  display: flex;
  align-items: center;
}

.total-info {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.total-text {
  margin-right: 15px;
}

.total-price {
  margin-right: 15px;
  font-size: 16px;
}

.total-price .price {
  font-size: 20px;
  color: #ff0036;
  font-weight: bold;
}

.discount-text {
  color: #ff0036;
}

.ant-btn[disabled] {
  opacity: 0.6;
}
</style>